package com.plantpoint.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.plantpoint.entity.bean.TemplateData;
import com.plantpoint.entity.vo.WxMssVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 * 发送订阅消息，本controller暂未完成
 * @date   2021/4/25 0025 18:29
 * @author JackeyTower
 */
@RestController
public class SendWxMessage {

    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.appsecret}")
    private String appsecret;

    /*
     * 发送订阅消息
     * */
    @GetMapping("/pushOneUser")
    public String pushOneUser() {
        return push("oDam25D9rq9ZxUFugnqSg6zqtxa0");//暂无openid
    }

    public String push(String openid) {
        RestTemplate restTemplate = new RestTemplate();
        //这里简单起见我们每次都获取最新的access_token（时间开发中，应该在access_token快过期时再重新获取）
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getAccessToken();
        //拼接推送的模版
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(openid);//用户的openid（要发送给那个用户，通常这里应该动态传进来的）
        wxMssVo.setTemplate_id("v25O_vSZbytvz7mLHHsDcXTsOu7EBX1JNkGPdbyhabs");//订阅消息模板id
        wxMssVo.setPage("pages/index/index");//需要跳转的页面，如没有则不填

        Map<String, TemplateData> m = new HashMap<>(3);
        m.put("thing1", new TemplateData("曼陀罗"));
        m.put("time2", new TemplateData("2020年12月12日 11:30"));
        m.put("number3", new TemplateData("5"));
        wxMssVo.setData(m);
        ResponseEntity<String> responseEntity =
                restTemplate.postForEntity(url, wxMssVo, String.class);
        return responseEntity.getBody();
    }


    @GetMapping("/getAccessToken")
    public String getAccessToken() {
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> params = new HashMap<>();
        params.put("APPID", appid);  //
        params.put("APPSECRET", appsecret);  //
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}", String.class, params);
        String body = responseEntity.getBody();
        JSONObject object = JSON.parseObject(body);
        String Access_Token = object.getString("access_token");
        String expires_in = object.getString("expires_in");
        System.out.println("有效时长expires_in：" + expires_in);
        return Access_Token;
    }
}

